<template>
  <div>
    <div class="btns">
      <button class="btn btn-middle" @click="newAdv">新增广告</button>
      <button class="btn btn-middle">批量删除</button>
    </div>
    <table>
      <thead>
        <tr class="text-c">
          <th><input type="checkbox" name="cbAll" @change="selectAll"></th>
          <th>广告ID</th>
          <th>广告名称</th>
          <th>广告位置</th>
          <th>广告类型</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody v-if="advList.length>0">
        <tr class="text-c" v-for="(item,key) in advList" :key="key">
          <td><input type="checkbox" name="cb" :value="item.id"></td>
          <td>{{ item.id }}</td>
          <td>{{ item.advName }}</td>
          <td>{{ item.advPosition }}</td>
          <td>{{ item.advType }}</td>
          <td>
            <router-link class="btn btn-small" :to="'/adManage/edit/'+item.id">编辑</router-link>
            <button class="btn btn-small" @click="del(item.id)">删除</button>
          </td>
        </tr>
      </tbody>
      <tbody v-else>
        <tr>
          <td colspan="6">没有数据！</td>
        </tr>
      </tbody>
    </table>
    <pagination :curPage="pNum" :totalPage="pTotal" :pageSize="pSize" :total="listTotal"></pagination>
  </div>
</template>

<script>
import $ from 'jquery'
import axios from 'axios'
import pagination from '../../components/pagination.vue'

export default {
  name: 'advList',
  components: { pagination },
  data () {
    return {
      advList: [],
      pNum: 1,
      pTotal: 100,
      pSize: 5,
      listTotal: 51
    }
  },
  methods: {
    newAdv () {
      this.$router.push('/adManage/add')
    },
    selectAll () { // 全选有问题
      let isChecked = document.getElementsByName('cbAll')[0].checked
      // let isChecked = $('input[name=cbAll]').attr('checked')
      if (isChecked === true) {
        $('input[name=cb]').attr('checked', false)
        $('input[name=cb]').attr('checked', true)
      } else {
        $('input[name=cb]').attr('checked', true)
        $('input[name=cb]').attr('checked', false)
      }
    },
    del (id) {
      let $this = this
      axios.post('/api/delAdv', {
        id: id
      }).then(function (res) {
        if (res.status === 200) {
          if (res.data.success === true) {
            alert('删除成功')
            $this.$router.push('/adManage')
          }
        }
      }).catch(function (err) {
        console.log(err)
      })
    }
  },
  mounted () {
    let $this = this
    axios.get('/api/advList')
      .then(function (res) {
        if (res.status === 200) {
          $this.advList = res.data
        }
      })
      .catch(function (err) {
        console.log(err)
      })
  }
}
</script>

<style scoped>
.btns {
  margin-bottom: 10px;
}
</style>
